package com.mike.common;

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.map.annotate.JsonSerialize;

import java.io.Serializable;

/**
 * Created by HP on 2018/2/28.
 */
/*通过设置JsonSerialize对象
    *当回传成功状态吗0时，msg和打他为null
    * 当回传错误信息(status,msg)时，data为null
    * 使用如下注解，则jackson不知道为null的属性进行包含和处理，key和value在返回值中都不存在
    * */
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> implements Serializable {



    private int status;
    private String msg;
    private T data;

    @JsonIgnore
    public boolean isSuccess(){return  this.status == ResponseCode.SUCCESS.getCode();}


    public int getStatus() {
        return status;
    }

    public String getMsg() {
        return msg;
    }

    public T getData() {
        return data;
    }

    private ServerResponse(int status) {
        this.status = status;
    }

    private ServerResponse(int status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    private ServerResponse(int status, T data) {
        this.status = status;
        this.data = data;
    }

    private ServerResponse(int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    //运行成功时的返回对象
    public static<T> ServerResponse<T> createSuccessResponse(){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
    }
    public static<T> ServerResponse<T> createSuccessResponse(T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
    }
    public static<T> ServerResponse<T> createSuccessResponse(String msg,T data){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
    }
    public static<T> ServerResponse<T> createSuccessMessageResponse(String msg){
        return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
    }
    //运行失败时的返回对象
    public static<T> ServerResponse<T> createErrorResponse(){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode());
    }
    public static<T> ServerResponse<T> createErrorMessageResponse(T data){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),data);
    }
    public static<T> ServerResponse<T> createErrorResponse(String msg,T data){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),msg,data);
    }
    public static<T> ServerResponse<T> createErrorMessageResponse(String errMsg){
        return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errMsg);
    }
    //其他返回类型
    public static<T> ServerResponse<T> createErrorCodeMsg(int errCode,String errMsg){
        return  new ServerResponse<T>(errCode,errMsg);
    }
}
